package cn.mw.cmdb.service.impl;


import cn.mw.cmdb.config.CustomizeThreadPool;
import cn.mw.cmdb.entity.cloudWisdom.CloudWisdomInstanceReportHistoryInfo;
import cn.mw.cmdb.entity.cloudWisdom.CloudWisdomReportParam;
import cn.mw.cmdb.entity.cloudWisdom.CloudWisdomServiceResponse;
import cn.mw.cmdb.enums.OperatorTypeDescEnum;
import cn.mw.microMonitorCommon.entity.common.FinanceReportChannelDto;
import cn.mw.microMonitorCommon.util.DateUtils;
import cn.mw.microMonitorCommon.util.HttpUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class CloudWisdomAsyncReportService {

    private static final String CREATE_PARAMS_URL = "/api/v1/open/ci/create";

    private static final String UPDATE_PARAMS_URL = "/api/v1/open/ci/modify/";
    private static final String SYSTEM_ERROR_MSG = "System Error!";

    @Async(CustomizeThreadPool.CloudWisdomReportThreadPool)
    public CompletableFuture<CloudWisdomInstanceReportHistoryInfo> doReport(CloudWisdomReportParam cloudWisdomReportParam, FinanceReportChannelDto financeReportChannelDto) {
        CloudWisdomInstanceReportHistoryInfo cloudWisdomInstanceReportHistoryInfo = new CloudWisdomInstanceReportHistoryInfo();
        try {
            cloudWisdomInstanceReportHistoryInfo.setReportDate(DateUtils.now());
            cloudWisdomInstanceReportHistoryInfo.setOperateType(cloudWisdomReportParam.getOperateType());
            cloudWisdomInstanceReportHistoryInfo.setRequestParam(cloudWisdomReportParam.getContent());
            cloudWisdomInstanceReportHistoryInfo.setInstanceId(cloudWisdomReportParam.getInstanceId());
            if (cloudWisdomReportParam.getInstanceInfoExtend() != null) {
                cloudWisdomInstanceReportHistoryInfo.setInstanceName(cloudWisdomReportParam.getInstanceInfoExtend().getInstanceName());
                cloudWisdomInstanceReportHistoryInfo.setModelName(cloudWisdomReportParam.getInstanceInfoExtend().getModelName());
                cloudWisdomInstanceReportHistoryInfo.setModelGroupName(cloudWisdomReportParam.getInstanceInfoExtend().getModelGroupName());
            }

            String requestUrl;
            boolean isAdd = OperatorTypeDescEnum.add.getCname().equals(cloudWisdomReportParam.getOperateType());
            if (isAdd) {
                requestUrl = String.format(Locale.ENGLISH, "%s%s", financeReportChannelDto.getServerUrl(), CREATE_PARAMS_URL);
            } else {
                requestUrl = String.format(Locale.ENGLISH, "%s%s%s", financeReportChannelDto.getServerUrl(), UPDATE_PARAMS_URL, cloudWisdomReportParam.getCiId());
            }

            String response = HttpUtils.sendPostRequest(requestUrl, JSON.toJSONString(cloudWisdomReportParam), getRequestHeader(financeReportChannelDto));
            if (StringUtils.isNotBlank(response)) {
                log.info("doReport result:{}", response);
                CloudWisdomServiceResponse serviceResponse = JSON.parseObject(response, CloudWisdomServiceResponse.class);
                if (serviceResponse.getCode() == 0) {
                    cloudWisdomInstanceReportHistoryInfo.setReportResult(true);
                    if (isAdd) {
                        cloudWisdomInstanceReportHistoryInfo.setRequestId(serviceResponse.getData().toString());
                    } else {
                        cloudWisdomInstanceReportHistoryInfo.setRequestId(cloudWisdomReportParam.getCiId());
                    }
                } else {
                    cloudWisdomInstanceReportHistoryInfo.setReportResult(false);
                    cloudWisdomInstanceReportHistoryInfo.setErrorMsg(serviceResponse.getMessage());
                }
            }
        } catch (Exception e) {
            cloudWisdomInstanceReportHistoryInfo.setReportResult(false);
            cloudWisdomInstanceReportHistoryInfo.setErrorMsg(SYSTEM_ERROR_MSG);
        }
        return CompletableFuture.completedFuture(cloudWisdomInstanceReportHistoryInfo);
    }

    private Map<String, String> getRequestHeader(FinanceReportChannelDto financeReportChannelDto) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("OperateModel", "HTTP_API");
        headers.put("appName", financeReportChannelDto.getAppName());
        headers.put("appKey", financeReportChannelDto.getUserName());
        headers.put("appSecret", financeReportChannelDto.getAuthToken());
        return headers;
    }
}
